<?php

namespace Phoo\db;

class Query implements \Iterator{
	private $db = null;
	private $className = null;
	private $query = array();
	
	function __construct($db,$className){
		$this->db = $db;
		$this->className = $className;
	}
	
	private function cursor(){
		if($this->cursor === null)
			$this->cursor = $this->db->find($this->query);
		
		return $this->cursor;
	}
	
	public function current() {
		return new $this->className($this->cursor()->current());
	}

	public function next() {
		$this->cursor()->next();
	}

	public function key() {
		return $this->cursor()->key();
	}
	
	public function valid() {
		return $this->cursor()->valid();
	}

	public function rewind() {
		$this->cursor()->rewind();
	}
	
	public function filter($key,$value){
		$matches = array();
		preg_match("/^(?<key>[^\s]+)(\s+(?<operator><=|<|=|>=|>|!=|in))?$/i",$key,$matches);
		
		$key = $matches["key"];
		$operator = strtolower($matches["operator"]);
		
		//The default operator is =
		if(empty($operator))
			$operator = "=";
			
		if($operator == "=")
			$this->query[$key] = $value;
			
		return $this;
	}
}